<?php

date_default_timezone_set('Europe/Bucharest');

error_reporting(-1);
ini_set('display_errors', '1');

$nest = "";
$type = "pagini";
define("HOSTNAME", "ceata.org");

// Verify file argument.
if (isset($argv[1]) && $argv[1] == '-t')
{
	$all = get_all_files("tpl");
	foreach ($all as $file)
	  {
	       if ($file == "") continue;
	       $file = $file.".tpl";
	       $type = get_type($file);
	       echo ucfirst($type).": ".$file."\n";
	       publish($file, $type);
          }
	update_sitemap();
}
else if (isset($argv[1]) && $argv[1] == '-h')
{
	update_sitemap();
}
else if (isset($argv[1]))
  {
      // Verify file name argument.
      if (substr($argv[1], -4) != ".tpl")
        {
            echo "Eroare: nu a fost specificat argumentul cu fișierul .tpl. Utilizare: php publică.php <fișier.tpl>\n";
            die();
        }

      // TODO: Filename should not start with '/' (should be relative)
      // TODO: Check if the file exists

      $type = get_type($argv[1]);

      // Publish or update the article.
      publish($argv[1], $type);
  }
// else if(isset($argv[1]) && $argv[1] == '-all')
//   {
//       // Get all articles templates.
//       $articles = glob("*.tpl");

//       // Publish or update all articles.
//       foreach ($articles as $article)
//         {
//             // Publish or update the article.
//             publish($article);
//         }
//  }
else
 {
      echo "Eroare: nu a fost specificat argumentul cu fișierul .tpl. Utilizare: php publică.php <fișier.tpl>\n";
      die();
 }

function get_all_files($ext)
{
     return explode("\n", shell_exec("find . -path ./formate -prune -o -name \"*.".$ext."\" -print | sed -e 's/\.".$ext."//g' | sort | sed -e \"s/\.\///g\""));
}

function get_type($file)
{
      $type = "pagini";

      $pos = strpos($file, "comunicate");
      if ($pos !== false && $pos == 0)
            $type = "comunicate";
      else
        {
  	    $pos = strpos($file, "evenimente");
	    if ($pos !== false && $pos == 0)
                $type = "evenimente";
        }

	return $type;
}

function get_news_brief($file)
{
	  $city = get_text($file, "city");
	  $country = get_text($file, "country");
	  $date = get_text($file, "date");
	  $brief = get_text($file, "brief");
	  $rodate = rodate($date);
          $brief = $city.", ".$country." -- ".$rodate[0].", ".$rodate[1]." -- ".$brief;

	  return $brief;
}

function get_event_brief($file)
{
	  $date = get_text($file, "date");
	  $hours = get_text($file, "hours");
	  $city = get_text($file, "city");
	  $country = get_text($file, "country");
	  $room = get_text($file, "room");
	  $host = get_text($file, "host");
	  $address = get_text($file, "address");
	  $brief = get_text($file, "brief");
	  $rodate = rodate($date);

	  $brief = $city.", ".$country." -- ".$rodate[0].", ".$rodate[1].", orele ".$hours." -- ".$room.", ".$host.", ".lcfirst($address).". ".$brief;

	  return $brief;
}

function get_brief($file, $type)
{
    $brief = "";

    if (!strcmp($type, "comunicate"))
      {
          $brief = get_news_brief($file);
      }
    else if (!strcmp($type, "evenimente"))
      {
	  $brief = get_event_brief($file);
      }

      return $brief;
}

function get_event_details($file)
{
	  $date = get_text($file, "date");
	  $rodate = rodate($date);
	  $hours = get_text($file, "hours");
	  $city = get_text($file, "city");
	  $country = get_text($file, "country");
	  $room = get_text($file, "room");
	  $host = get_text($file, "host");
	  $address = get_text($file, "address");
	  $brief = get_text($file, "brief");

	  $contactname = get_text($file, "contactname");
	  $contactmail = tomail(get_text($file, "contactmail"));
	  $contactphone = get_text($file, "contactphone");

	  $details = "<table class=\"detalii\">";
	  $details .= "<tr><th>Data</th><td>".$rodate[1]."</td></tr>";
	  $details .= "<tr><th>Orele</th><td>".$hours."</td></tr>";
	  $details .= "<tr><th>Orașul</th><td>".$city.", ".$country."</td></tr>";
	  $details .= "<tr><th>Sala</th><td>".$room."</td></tr>";
	  $details .= "<tr><th>Gazda</th><td>".$host."</td></tr>";
	  $details .= "<tr><th>Adresa</th><td>".$address."</td></tr>";

	  if ($contactname)
            {
	        $details .= "<tr><th>Coordonator</th><td>";
		$details .= "<table class=\"contact\">";
	        $details .= "<tr><td>".$contactname."</td></tr>";

		if ($contactmail)
		    $details .= "<tr><td>".$contactmail."</td></tr>";

		if ($contactphone)
		    $details .= "<tr><td>".$contactphone."</td></tr>";

		$details .= "</table>";
		$details .= "</td></tr>";
            }

	  $details .= "<tr><th>Calendar</th><td>vCal, iCal</td></tr>";
	  $details .= "</table>";

	  return $details;
}

function get_press_release($file)
{
	$press = get_text($file, "pressrelease");
	if ($press)
	   $press = "Pentru mai multe informații, vă invităm să citiți <a href=\"../comunicate/".$press."\">comunicatul oficial</a>.";

	return $press;
}

function get_content($file, $type)
{
    $content = get_html($file, "content");

    if (!strcmp($type, "evenimente"))
      {
          $details = get_event_details($file);
	  $press = get_press_release($file);
	  
	  $report = get_html($file, "report");
	  if ($report)
	    $report = "<h3 id='raport'>Raportul evenimentului</h3>".$report;

	  $content = $details.$content.$report.$press;
      }

    return $content;
}

function get_press_contact($file, $type)
{
    $press = "";

    if (!strcmp($type, "comunicate"))
      {
          $press = "<h3>Contact pentru presă</h3>";
      }
    else if (!strcmp($type, "evenimente"))
      {
          $press = "<h3>Coordonatorul evenimentului</h3>";
      }

      $contactname = get_text($file, "contactname");
      $contactfunc = get_text($file, "contactfunc");
      $contactmail = tomail(get_text($file, "contactmail"));
      $contactphone = get_text($file, "contactphone");

	  if ($contactname)
            {
	        $press .= "<p>";
	        $press .= $contactname."<br />";

		if ($contactfunc)
         	    $press .= $contactfunc.", Fundația Ceata<br />";

		if ($contactmail)
		    $press .= $contactmail."<br />";

		if ($contactphone)
		    $press .= $contactphone."<br />";

		$press .= "</p>";
            }
	  else
	    $press = "";

      return $press;
}

/**
 * Publish function.
 *
 * Publishes a post by creating a HTML file of the post and update the news page.
 *
 * @param $file
 *   File name of the article content.
 */
function publish($file, $type)
{
    global $news_templates_path;

    $nested_level = substr_count($file, '/');
    $nested = str_repeat("../", $nested_level);

    // Read header template.
    $article = read_template("formate/header.tpl");

    if (strcmp($type, "pagini"))
      {
	  // Read content template.
	  $article .= read_template("formate/article.tpl");

          $brief = get_brief($file, $type);
          // Update the published date.
	  $article = str_replace("<!-- brief -->", $brief, $article);

   	   $press_contact = get_press_contact($file, $type);
	   // Update the the press contact. 
	   $article = str_replace("<!-- press -->", $press_contact, $article);
      }
    else
      {
           $article .= read_template("formate/page.tpl");
      }

    // Read the article.
    $article .= read_template("formate/footer.tpl"); 

    // Read footer template.
    $article_content = read_template($file);
 
    // Get the article data.
    $title = get_text($file, "title");

    $content = get_content($file, $type);

    // Update the the site title. 
    $article = str_replace("<!-- site-title -->", $title . " &mdash; Fundația Ceata &mdash; Ceata eliberează artele și tehnologiile actuale", $article);

    // Update the the title. 
    $article = str_replace("<!-- title -->", $title, $article);

    $article = str_replace("<!-- breadcrumbs -->", get_breadcrumbs($file), $article);

    // Update the the content. 
    $article = str_replace("<!-- content -->", $content, $article);

    // Update the article style path.
    $article = str_replace("stylesheet\" href=\"", "stylesheet\" href=\"".$nested, $article);

    // Update the article favicon.
    $article = str_replace("shortcut icon\" href=\"", "shortcut icon\" href=\"".$nested, $article);

    // Update the article images path.
    $article = str_replace("<img src=\"", "<img src=\"".$nested, $article);

    // Get the article file name without extention.
    $filename = substr_replace($file,"",-4);

    if (file_exists($filename.".html"))
      {
           update_sitemap();
      }

    // Create or update the article.
    create_page($filename.".html", $article);

    echo "-- ".$filename.".html - articol publicat/actualizat.\n";

    if (strcmp($type, "pagini"))
      {
           // Generate feed from  published articles.
           generate_feed($type);

          // Generate news page.
          generate_news_page($type);
      }
}

function get_breadcrumbs($file)
{
    $trail = "";
    $count = 0;

    $breadcrumbs = "<li><a href='/'>Prima pagină</a></li>";

    $file = strtok($file, ".");
    $lvls = substr_count($file, "/");

    $parent = strtok($file, "/");
    while ($parent)
    {
	$trail .= $parent;

	$title = "";
        if (file_exists($trail.".tpl"))
	    $title = get_text($trail.".tpl", "title");
	else if (is_link($trail.".html"))
        {
            $count++;
            $trail .= "/";
            $parent = strtok("/");
	    continue;
        }
        else if (file_exists($trail.".html"))
	    $title = ucfirst($trail);
	else $title = "Pagină necunoscută";

	if ($count < $lvls)
            $breadcrumbs .= "<li> &raquo; <a href='"."/".$trail.".html'>".$title."</a></li>";
        else
	    $breadcrumbs .= "<li> &raquo; ".$title."</li>";

	$trail .= "/";
	$count++;
        $parent = strtok("/");
    }

    return $breadcrumbs;
}

function update_sitemap()
{
    // Read header template.
    $article = read_template("formate/header.tpl");

    $article .= read_template("formate/page.tpl");

    // Read the footer template.
    $article .= read_template("formate/footer.tpl"); 

    $title = "Planul sitului";

    // Update the the site title. 
    $article = str_replace("<!-- site-title -->", $title . "  &mdash; Fundația Ceata &mdash; Ceata eliberează artele și tehnologiile actuale", $article);

    // Update the the title. 
    $article = str_replace("<!-- title -->", $title, $article);

    $all = get_all_files("html");

    $content = "<ul>";
    $last = "";
    $level = 1;

    foreach ($all as $file)
      {
          if ($file == "" || is_link($file.".html")) continue;

 	  if ($last != "" && get_parent($file) == $last)
	     {
	         $content .= "<ul>";
		 $level++;
             }
          else
	    {
	        $uplevels = get_uplevels($last, get_common_parent($file, $last));
	        for ($i = 0; $i < $uplevels && $level > 1; $i++)
                  {
	            $content .= "</ul>";
		    $level--;
                  }
            }

          if ($file == "comunicate" || 
              $file == "evenimente" ||
              $file == "planul-sitului" || 
	      $file == "prima-pagină"
             )
            {
                 $title = str_replace("-", " ", ucfirst($file));
            }
	  else
            {
                $article_content = read_template($file.".tpl");
 
                // Get the article data.
                $title = get_text($file.".tpl", "title");
            }

          $content .= "<li><a href=\"".$file."\">".$title."</a></li>";

	  $last = $file;
      }
    $content .= "</ul>";

    // Update the the content. 
    $article = str_replace("<!-- content -->", $content, $article);

    $sitemap = "planul-sitului.html";

    // Create or update the article.
    create_page($sitemap, $article);

    echo "-- ".$sitemap." - pagină publicată/actualizată.\n";
}

function get_parent($file)
{
    $parent = "";

    $pos = strrpos($file, "/");

    if ($pos !== false)
      {
          $parent = substr($file, 0, $pos);
      }

    return  $parent;
}

function get_common_parent($file1, $file2)
{
    $found = strpos("/".$file2, "/".get_parent($file1));
    while ($found === false)
      {
          $file1 = get_parent($file1);
          $found = strpos("/".$file2, "/".get_parent($file1));
      }

    return get_parent($file1);
}

function get_uplevels($file, $path)
{
    $uplevels = 0;

    $level1 = substr_count($file, '/');
    $level2 = substr_count($path, '/');

    $uplevels = $level1 - $level2;

    if ($path != "" && strpos($file, $path) !== false)
        $uplevels--;

    return $uplevels;
}

/*
 * Get the text field function.
 *
 * Get the field from article in the original source. The source is a HTML 
 * formatted '.tpl' file. 
 *
 * @param $file
 *   The original article content file (a '.tpl' file). 
 *
 * @param $field
 *   The field from the original article content file (a '.tpl' file). 
 *
 * @return
 *   Returns a string contaning the requested field. 
 */
function get_text($file, $field)
{
    // Create dom object.
    $doc = new DOMDocument();
 
    // Load oricinal article.
    $doc->loadHTMLFile($file);

    // Get article field.
    $element = $doc->getElementById($field);

    if ($element == NULL)
        return "";

    $text = $element->textContent;
    return $text;
}

function get_tag_value($file, $field)
{
    // Create dom object.
    $doc = new DOMDocument();
 
    // Load oricinal article.
    $doc->loadHTMLFile($file);

    // Get article field.
    $elements = $doc->getElementsByTagName($field);
    $element = $elements->item(0);

    if ($element == NULL)
        return "";

    $text = $element->textContent;
    return $text;
}

/*
 * Get the content function.
 *
 * Get the content of a field from the original source. The source is a HTML 
 * formatted '.tpl' file. 
 *
 * @param $file
 *   The original field content file (a '.tpl' file). 
 *
 * @param $field
 *   The field from the original article file (a '.tpl' file). 
 *
 * @return
 *   Returns a string contaning the field content. 
 */
function get_html($file, $field)
{
    // Create dom object.
    $doc = new DOMDocument('1.0', 'UTF-8');
 
    // Load oricinal article.
    $doc->loadHTMLFile($file);

    // Get article content.
    $element = $doc->getElementById($field);

    if ($element == NULL)
        return "";

    $content = get_inner_html($element);

    return $content;
}

/**
 * Read template function.
 *
 * Reads the content of a page template.
 *
 * @param $template_file
 *   A string, template file name.
 */
function read_template($template_file)
{
    // Get template content.
    $template_content = file_get_contents($template_file);

    return $template_content;
}

/**
 * Create page function.
 *
 * Creates or update a HTML page.
 *
 * @param $page_name
 *   A string, page file name.
 *
 * @param $content
 *   A string, page content.
 */
function create_page($page_name, $content)
{
    // Open file for writing.
    $file = fopen($page_name,"w");

    // Write content to file.
    fwrite($file, $content);

    fclose($file);
}

/**
 * Truncate text function.
 *
 * Truncates a text.
 *
 * @param $text
 *   Text to be truncated.
 * @param $max_text_length
 *   The length of truncated text.
 * @param $append
 *   String to append to the end of truncated text (such as '...').
 * @param $strip
 *   Strip tags or not.
 *
 * @return
 *   Truncated text or an empty string.
 */
function truncate_text($text, $text_length, $append = "", $strip = TRUE) 
{
    // Verify text.
    if ( empty($text) ) return '';

    // Verify wether to strip tags.
    if ($strip)
      {
          // Strip tags.
          $text = strip_tags($text);
      }

    if (strlen($text) > $text_length) 
      {
          // Get the the substring of legn $text_length.
          $text = mb_substr($text, 0, $text_length, 'UTF-8');

          // Add $append string.
          $text .= " ".$append;
      }

    return $text;
}



/**
 * Generate freed function.
 *
 * Creates or updates the RSS file from the list published articles.
 *
 * @param $limit
 *   Number of feeds.
 */
function generate_feed($type, $limit = 10)
{
    // Get the list of articles templates.
    $articles = glob($type."/*.tpl");

    // Create articles list.
    foreach ($articles as $article)
      {
          $list[$article] = get_text($article, "date");  
      }
         
    // Sort articles by descending date.
    arsort($list);

    // Limit the number of articles.
    $list = array_slice($list, 0, $limit);

    $rss  = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
    $rss .= '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" 
        xmlns:georss="http://www.georss.org/georss">'."\n";
    $rss .= '<channel>'."\n";
    $rss .= '<title>'.ucfirst($type).' — Fundația Ceata — Ceata eliberează artele și tehnologiile actuale</title>'."\n";
    $rss .= '<link>http://ceata.org/'.$type.'</link>'."\n";
    $rss .= '<description>
        Ceata eliberează artele și tehnologiile actuale</description>'."\n";
    $rss .= '<language>ro</language>'."\n";
    $rss .= '<ttl>480</ttl>'."\n";

    foreach($list as $key => $article)
      {
          $rss .= '<item>'."\n";
          $rss .= '<title><![CDATA['.get_text($key, "title").']]></title>'."\n";
          $rss .= '<description><![CDATA['
              .get_brief($key, $type).']]></description>'."\n"; 
          $rss .= '<pubDate>'
              .gmdate(DATE_RSS, strtotime(get_text($key, "date"))).'</pubDate>'."\n";

          // Get the article file name without extention.
          $filename = substr_replace($key,"",-4);

          $rss .= '<link>http://'.HOSTNAME.'/'.$filename.'</link>'."\n";
          $rss .= '</item>'; 
      }

    $rss .= '</channel>'."\n";
    $rss .= '</rss>'."\n";

    create_page($type.'.rss', $rss);

    echo "-- ".$type.".rss - flux de RSS creat/actualizat.\n";
}

/**
 * Generate news page function.
 *
 * Creates or updates the nwes page.
 *
 */
function generate_news_page($type)
{
    // Get the list of articles templates.
    $articles = glob($type."/*.tpl");

    // Create articles list.
    foreach ($articles as $article)
      {
          $list[$article] = get_text($article, "date");  
      }
         
    // Sort articles by descending date.
    arsort($list);

    $news_page_content = "";

    foreach($list as $key => $article)
      {
          $article = '<li class="">';

          // Get the article file name without extention.
          $filename = substr_replace($key,"",-4);

	  $rodate = rodate(get_text($key, "date"));

          $article .= '<a href="'.$filename.'" class="titlu">'
              .get_text($key, "title").'</a>';
          $article .= '<span class="data">'
              .$rodate[1].'</span>';
          $article .= '<div class="rezumat"><p>'.get_brief($key, $type).'</p></div>'; 
          $article .= '</li> <!-- .aerisit -->'; 

          $news_page_content .= $article;
      }

    // Read header template.
    $news_page = read_template("formate/header.tpl");
    
    // Read content template.
    $news_page .= read_template("formate/".$type.".tpl");

    // Read footer template.
    $news_page .= read_template("formate/footer.tpl"); 

    // Update the the site title. 
    $news_page = str_replace("<!-- site-title -->", ucfirst($type)."  &mdash; Fundația Ceata &mdash; Ceata eliberează artele și tehnologiile actuale", $news_page);

    // Update the content. 
    $news_page = str_replace("<!-- news list -->", $news_page_content, $news_page);

    $news_page = str_replace("<!-- breadcrumbs -->", get_breadcrumbs($type.".html"), $news_page);

    create_page($type.'.html', $news_page);

    echo "-- ".$type.".html - pagină de știri publicată/actualizată.\n";
}

function get_inner_html($node) 
{
    $innerHTML = '';
    $children = $node->childNodes;

    foreach ($children as $child) 
      {
          $innerHTML .= $child->ownerDocument->saveXML($child);
      }
 
    return $innerHTML;
}

function tomail($address)
{
	return "<a href=\"mailto:".$address."\">".$address."</a>";
}

function rodate($date)
{
	$time = strtotime(substr($date, 2));
	$strdate = strftime(('%A %d %B %Y'), $time);
	$rodate = _rodate($strdate);

	return $rodate;
}

function _rodate($strdate)
{
	$day = strtok($strdate, " ");

	switch ($day)
	{
		case "Monday":
		     $day = "luni";
		     break;
		case "Tuesday":
		     $day = "marți";
		     break;
		case "Wednesday":
		     $day = "miercuri";
		     break;
		case "Thursday":
		     $day = "joi";
		     break;
		case "Friday":
		     $day = "vineri";
		     break;
		case "Saturday":
		     $day = "sâmbătă";
		     break;
		case "Sunday":
		     $day = "duminică";
	}

	$dayn = ltrim(strtok(" "), "0");

	$month = strtok(" ");

	switch ($month)
	{
		case "January":
		     $month = "ianuarie";
		     break;
		case "February":
		     $month = "februarie";
		     break;
		case "March":
		     $month = "martie";
		     break;
		case "April":
		     $month = "aprilie";
		     break;
		case "May":
		     $month = "mai";
		     break;
		case "June":
		     $month = "iunie";
		     break;
		case "July":
		     $month = "iulie";
		     break;
		case "August":
		     $month = "august";
		     break;
		case "September":
		     $month = "septembrie";
		     break;
		case "October":
		     $month = "octombrie";
		     break;
		case "November":
		     $month = "noiembrie";
		     break;
		case "December":
		     $month = "decembrie";
	}

	$year = strtok(" ");

	$daydate[0] = $day;
	$daydate[1] = $dayn . " " . $month . " " . $year;

	return $daydate;
}

?>
